package com.npr.service;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.npr.dao.DiscussPostMapper;
import com.npr.entity.DiscussPost;
import com.npr.util.RedisKeyUtil;
import com.npr.util.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostService {
    @Autowired
    private static Logger logger = LoggerFactory.getLogger(DiscussPostService.class);
    @Autowired
    private DiscussPostMapper discussPostMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${caffeine.posts.max-size}")
    private int maxSize;
    @Value("${caffeine.posts.expire-seconds}")
    private int expireSecond;


    //Caffeine核心接口：Cache,LoadingCache,AsyncLoadingCache

    //帖子列表的缓存
    private LoadingCache<String,List<DiscussPost>> postListCache;

    //帖子总数的缓存
    private LoadingCache<Integer,Integer> postRowCache;

    @PostConstruct
    public void init(){
        //初始化列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSecond, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(@NonNull String key) throws Exception {
                        if(key==null||key.length()==0){
                            throw new IllegalArgumentException("参数错误");
                        }
                        String[] params = key.split(":");
                        if (params == null||params.length!=2){
                            throw new IllegalArgumentException("参数错误");
                        }
                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);
                        //扩展：可以自己再加一个二级缓存 Redis -> Mysql
                        String redisKey = RedisKeyUtil.getHotPostListKey(offset,limit);
                        // 如果redis中不存在就去数据库里查，查到了就更新到redis中，然后返回作为本地缓存的同步
                        if (!redisTemplate.hasKey(redisKey)){
                            logger.debug("redis中没有缓存");
                            logger.debug("load post list from DB.");
                            List<DiscussPost> result = discussPostMapper.selectDiscussPosts(0,offset,limit,1);
                            for(DiscussPost post : result){
                                redisTemplate.opsForZSet().add(redisKey,post,post.getScore());
                            }
                            redisTemplate.expire(redisKey,60*7 ,TimeUnit.SECONDS);
                            return result;
                        } else {
                            logger.debug("redis中有缓存");
                            // 要查看redis数据是否过期
                            System.out.println(redisTemplate.getExpire(redisKey));
                            boolean isExpired = redisTemplate.getExpire(redisKey) < 0 ? true : false;
                            if (isExpired){
                                // 如果过期的话，就删去key，就去数据库里查
                                logger.debug("redis expired!");
                                redisTemplate.delete(redisKey);
                                logger.debug("load post list from DB.");
                                List<DiscussPost> result = discussPostMapper.selectDiscussPosts(0,offset,limit,1);
                                for(DiscussPost post : result){
                                    redisTemplate.opsForZSet().add(redisKey,post,post.getScore());
                                }
                                redisTemplate.expire(redisKey,7*60 ,TimeUnit.SECONDS);
                                return result;
                            } else {
                                Set<DiscussPost> posts = redisTemplate.opsForZSet().reverseRange(redisKey, offset, limit);
                                logger.debug("redis len: " + redisTemplate.opsForZSet().zCard(redisKey));
                                logger.debug("load post list from redis.");
                                List<DiscussPost> list = new ArrayList<>();
                                for (DiscussPost post : posts) {
                                    list.add(post);
                                }
                                return list;
                            }
                        }
                        /*logger.info("从DB中获取帖子列表数据");
                        return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);*/
                    }
                });
        //初始化贴子总数缓存
        postRowCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSecond,TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post rows from DB");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });

    }
    /**
     * 查询帖子
     * @param userId yonghuid
     * @param offset 第一个数数据是哪条
     * @param limit 每页多少条数据
     * @return
     */
    public List<DiscussPost> findDiscussPosts(int userId,int offset,int limit,int orderMode){
        if (userId == 0 && orderMode == 1){
            return postListCache.get(offset+":"+limit);
        }
        logger.debug("load post list from DB");
        return discussPostMapper.selectDiscussPosts(userId,offset,limit,orderMode);
    }

    /**
     * 查询帖子数
     * @param userId 用户id
     * @return
     */
    public int findDiscussPostRows(int userId){
        if(userId == 0){
            return postRowCache.get(userId);
        }
        logger.debug("load post rows from DB");
        return discussPostMapper.selectDiscussPostRows(userId);
    }
    public int addDiscussPost(DiscussPost post){
        if(post==null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        //先转义HTML标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        //过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPostMapper.insertDiscussPost(post);
    }
    public DiscussPost findDiscussPostById(int id){
        return discussPostMapper.selectDiscussPostById(id);
    }
    public int updateCommentCount(int id,int commentCount){
        return discussPostMapper.updateCommentCount(id,commentCount);
    }
    public int updateType(int id,int type){
        return discussPostMapper.updateType(id,type);
    }
    public int updateStatus(int id, int status){
        return discussPostMapper.updateStatus(id,status);
    }
    public int updateScore(int id,double score){
        return discussPostMapper.updateScore(id, score);
    }
}
